from xlrd import open_workbook

from tools.yaml_reader import File


class ExcelReader(File):
    def __init__(self, excel_path: str, sheet: [int, str], excel_title: bool = True):
        """
        Excel 文件中内容如下：
        A  B  C
        A1 B1 C1
        A2 B2 C3

        excel_title 为 True：
        读取格式：[{A: A1, B: B1, C: C1}, {A: A2, B: B2, C: C2}]
        excel_title 为 False：
        读取格式：[[A, B, C], [A1, B1, C1], [A2, B2, C3]]

        :param excel_path:
        :param sheet:
        :param excel_title:
        """
        super(ExcelReader, self).__init__(excel_path)
        self._sheet = sheet
        self._excel_title = excel_title
        self._data = []

    @property
    def data(self):
        if not self._data:
            work_book = open_workbook(self._file_path)
            if not isinstance(self._sheet, (int, str)):
                raise TypeError("excel 文件的表格：{} 不存在".format(self._sheet))
            if isinstance(self._sheet, int):
                s = work_book.sheet_by_index(self._sheet)
            else:
                s = work_book.sheet_by_name(self._sheet)

            if self._excel_title:
                title = s.row_values(0)
                for col in range(1, s.nrows):
                    self._data.append(dict(zip(title, s.row_values(col))))
            else:
                for col in range(0, s.nrows):
                    self._data.append(s.row_values(col))

        return self._data
